package com.wctj.api.base.utils;

import cn.hutool.core.map.MapUtil;
import com.wctj.api.base.enums.ApiCode;
import com.wctj.api.base.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @Description:
 * @Author: lzg
 */
@Slf4j
public class HttpClientUtil {

    public static final int TIMEOUT = 30000;

    public static final int MAX_TOTAL_CONNECTIONS = 1000;

    public static final int MAX_CONNECTIONS_PER_HOST = 100;

    public static final HttpClient httpClient;

    static {
        HttpClientParams httpClientParams = new HttpClientParams();
        httpClientParams.setConnectionManagerTimeout(TIMEOUT);
        HttpConnectionManager httpConnectionManager = new MultiThreadedHttpConnectionManager();
        HttpConnectionManagerParams params = new HttpConnectionManagerParams();
        params.setMaxTotalConnections(MAX_TOTAL_CONNECTIONS);
        params.setDefaultMaxConnectionsPerHost(MAX_CONNECTIONS_PER_HOST);
        httpConnectionManager.setParams(params);
        httpClient = new HttpClient(httpClientParams, httpConnectionManager);
    }


    /**
     * 发送Post请求
     *
     * @param url
     * @param map
     * @return
     * @throws Throwable
     */
    public static String post(String url, Map<String, String> headers,Map<String, String> map) throws Exception {
        PostMethod methodPost = new PostMethod(url);
        map.forEach(methodPost::addParameter);
        if(MapUtils.isNotEmpty(headers)){
            headers.forEach(methodPost::addRequestHeader);
        }
        httpClient.executeMethod(methodPost);
        String responsePost = new String(methodPost.getResponseBody(), StandardCharsets.UTF_8);
        methodPost.releaseConnection();
        return responsePost;
    }

    public static String get(String url, Map<String, String> headers, Map<String, String> map) throws Exception {
        url = url.concat("?").concat(MapUtil.join(map, "&", "="));
        log.info("send get :{}", url);
        GetMethod methodPost = new GetMethod(url);
        if (MapUtils.isNotEmpty(headers)) {
            headers.forEach(methodPost::addRequestHeader);
        }
        httpClient.executeMethod(methodPost);
        String responsePost = new String(methodPost.getResponseBody(), StandardCharsets.UTF_8);
        log.info("response :{}", responsePost);
        methodPost.releaseConnection();
        return responsePost;
    }

    public static String get(String url) throws Exception {
        log.info("send get :{}", url);
        GetMethod methodPost = new GetMethod(url);
        httpClient.executeMethod(methodPost);
        String responsePost = new String(methodPost.getResponseBody(), StandardCharsets.UTF_8);
        log.info("response :{}", responsePost);
        methodPost.releaseConnection();
        return responsePost;
    }

    /**
     * 发送Post请求
     *
     * @param url
     * @param headers
     * @return
     * @throws Throwable
     */
    public static String postJSON(String url, Map<String, String> headers, String json) throws Exception {
        PostMethod methodPost = new PostMethod(url);
        try {
            methodPost.addRequestHeader("Content-Type", "application/json");
            if (MapUtils.isNotEmpty(headers)) {
                headers.forEach(methodPost::addRequestHeader);
            }
            methodPost.setRequestEntity(new StringRequestEntity(json, "application/json;charset=utf-8", "UTF-8"));
            httpClient.executeMethod(methodPost);
            InputStream inputStream = methodPost.getResponseBodyAsStream();
            InputStreamReader streamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
            BufferedReader br = new BufferedReader(streamReader);
            StringBuilder builder = new StringBuilder();
            String str;
            while ((str = br.readLine()) != null) {
                builder.append(str);
            }
            br.close();
            return builder.toString();
        } catch (Exception e) {
            log.error("cHttpClientUtil.postJSON has error", e);
            throw new CustomException(ApiCode.HTTP_REQUEST_FAIL,e.getMessage());
        } finally {
            methodPost.releaseConnection();
        }
    }


}
